package com.bwie.service.impl;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbUserService;
import com.bwie.mapper.TbUserMapper;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.R;
import com.bwie.utils.Result;
import com.bwie.vo.LoginVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.concurrent.TimeUnit;

/**
 * @author lenovo
 * @description 针对表【tb_user(用户表)】的数据库操作Service实现
 * @createDate 2025-06-06 14:01:41
 */
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser>
        implements TbUserService {

    @Autowired
    TbUserMapper tbUserMapper;

    @Autowired
    StringRedisTemplate redisTemplate;


    @Override
    public Result sendCode(String mobile) {
        //验证手机号
        boolean ok = Validator.isMobile(mobile);
        if (!ok) {
            return Result.error().setMsg("手机号格式不正确");
        }

        TbUser user = tbUserMapper.selectOne(
                new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserMobile, mobile)
        );
        if (user == null) {
            //若用户不存在，注册用户
            user = new TbUser();
            user.setUserMobile(mobile);


            user.readyCreate(null);


            tbUserMapper.insert(user);

        }

        //生成验证码
        String code = RandomUtil.randomNumbers(4);

        //保存验证码并发送
        String key = "login-" + mobile;

        //放入缓存
        redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES);
        //发送
        MobileMessageUtil.sendMobileMessage(mobile, code);

        return Result.ok().setData(code);
    }


    @Override
    public Result login(LoginVo loginVo) {
        //判断验证码是否正确
        String key = "login-" + loginVo.getMobile();
        String redisCode = redisTemplate.opsForValue().get(key);
        if (redisCode == null) {
            return Result.error().setMsg("验证码已过期");
        }
        //判断验证码是否正确
        if (!redisCode.equals(loginVo.getCode())) {
            return Result.error().setMsg("验证码错误");
        }

        //获取用户信息
        TbUser user = tbUserMapper.selectOne(
                new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserMobile, loginVo.getMobile())
        );
        if (user == null) {
            //若用户不存在，注册用户
            return Result.error().setMsg("用户不存在");
        }


        //存token
        String tokenKey = "token-" + user.getUserId();

        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", user.getUserId())
                .claim("realName", user.getRealName())
                .claim("userEmail", user.getUserEmail())
                .compact();

        redisTemplate.opsForValue().set(tokenKey, token);

        user.setToken(token);

        return Result.ok().setData(user);
    }

}




